package com.itheima.reggie.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理类
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLException.class)
    public R<String> handlerSQLException(SQLException exception) {
        String ex = exception.getMessage();
        log.error("[发生数据库异常],{}", ex);
        if (exception.getMessage().contains("Duplicate entry")) {
            String[] split = exception.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error("数据库发送异常，不允许数据重复" + msg);
        } else if (exception.getMessage().contains("Data truncation")) {
            return R.error("数据库异常,数据太长");
        } else {
            return R.error("数据库未知异常");
        }
    }


    //自定义异常处理
    @ExceptionHandler(CustomException.class)
    public R<String> handlerRuntimeException(CustomException exception) {
        String ex =exception.getMessage();
        log.error("[发生数据库异常],{}", ex);
        return R.error(ex);
    }
}
